/*
 * Chastoslov
 * Copyright (C) 2009 Alexandr Stroghov
 * 
 * stroghov@gmail.com
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the 
 * GNU General Public License, version 2, as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if 
 * not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
 * MA 02111-1307 USA
*/
package world.ah.wf.guiclient;
import java.awt.Frame;
import java.awt.Dimension;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ComponentEvent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JPanel;

public class DialogUser extends JDialog {
  private ConnectionAssistant connAssist;
  public void setConnAssist(ConnectionAssistant connAssist) {this.connAssist = connAssist;};
  //
  private String currentUserLoginLabel = "Current user login";
  
  //
  private JButton bClose = new JButton();
  private JTextField tfReaderName = new JTextField();
  private JLabel labReaderName = new JLabel();
  private JButton bChangeUserName = new JButton();
  private JButton bDeleteUser = new JButton();
  private JButton bNewUser = new JButton();
  private JLabel labCurrentUserLogin = new JLabel();
  private GridBagLayout gridBagLayout1 = new GridBagLayout();
  private JPanel jPanel1 = new JPanel();

  public DialogUser() {this(null, "", false);}

  /**
   * 
   * @param parent
   * @param title
   * @param modal
   */
  public DialogUser(Frame parent, String title, boolean modal) {
    super(parent, title, modal);
    try {jbInit();} catch(Exception e) {e.printStackTrace();}
    // Язык (не предполагается переустановка языка во время работы с формой)
    setLang();
    //
    General.centerFrame(this);
    tfReaderName.getDocument().addDocumentListener(new DocumentListener () {
      public void changedUpdate(DocumentEvent e) {}
      public void insertUpdate(DocumentEvent e) {setICanChangeUserName(true);}
      public void removeUpdate(DocumentEvent e) {setICanChangeUserName(true);}
    });
    //


    

  }

  private void jbInit() throws Exception {
    this.setSize(new Dimension(400, 235));
    this.setResizable(false);
    this.getContentPane().setLayout(gridBagLayout1);
    this.setTitle("User");
    this.setDefaultCloseOperation(0);
    this.addWindowListener(new java.awt.event.WindowAdapter()
      {
        public void windowClosing(WindowEvent e)
        {
          this_windowClosing(e);
        }
      });
    this.addComponentListener(new java.awt.event.ComponentAdapter()
      {
        public void componentShown(ComponentEvent e)
        {
          this_componentShown(e);
        }
      });
    bClose.setText("Close");
    bClose.setPreferredSize(new Dimension(90, 25));
    bClose.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          bClose_actionPerformed(e);
        }
      });
    tfReaderName.setSize(new Dimension(370, 20));
    labReaderName.setLabelFor(tfReaderName);
    labReaderName.setText("User name");
    bChangeUserName.setText("Change user name");
    bChangeUserName.setEnabled(false);
    bChangeUserName.setPreferredSize(new Dimension(130, 25));
    bChangeUserName.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          ChangeUserName_actionPerformed(e);
        }
      });
    bNewUser.setText("New user");
    bNewUser.setPreferredSize(new Dimension(130, 25));
    bNewUser.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          bNewUser_actionPerformed(e);
        }
      });
    labCurrentUserLogin.setLabelFor(tfReaderName);
    labCurrentUserLogin.setText(currentUserLoginLabel + ": ");
    bDeleteUser.setText("Delete user");
    bDeleteUser.setPreferredSize(new Dimension(130, 25));
    bDeleteUser.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          bDeleteUser_actionPerformed(e);
        }
      });
    this.getContentPane().add(labCurrentUserLogin, new GridBagConstraints(0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(10, 13, 0, 3), 0, 0));
    this.getContentPane().add(bNewUser, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(15, 10, 0, 7), 0, 0));
    this.getContentPane().add(bChangeUserName, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 10, 0, 7), 0, 0));
    this.getContentPane().add(labReaderName, new GridBagConstraints(0, 1, 2, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(10, 13, 2, 3), 0, 0));
    this.getContentPane().add(tfReaderName, new GridBagConstraints(0, 2, 2, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 10, 0, 0), 0, 0));
    this.getContentPane().add(bClose, new GridBagConstraints(1, 5, 1, 1, 0.0, 1.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, new Insets(10, 0, 10, 0), 0, 0));
    this.getContentPane().add(bDeleteUser, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.HORIZONTAL, new Insets(5, 7, 0, 0), 0, 0));
    this.getContentPane().add(jPanel1, new GridBagConstraints(2, 0, 1, 6, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
  }
  /** Устанавливает язык интерфейса */
  public void setLang() {
    String s;
    s = General.getLangItem("СurrentUserLogin"); if(s.length() > 0) currentUserLoginLabel = s;
    s = General.getLangItem("User"); if(s.length() > 0) this.setTitle(s);
    s = General.getLangItem("Close"); if(s.length() > 0) bClose.setText(s);
    s = General.getLangItem("UserName"); if(s.length() > 0) labReaderName.setText(s);
    s = General.getLangItem("ChangeUserName"); if(s.length() > 0) bChangeUserName.setText(s);
    s = General.getLangItem("NewUser"); if(s.length() > 0) bNewUser.setText(s);
    s = General.getLangItem("DeleteUser"); if(s.length() > 0) bDeleteUser.setText(s);
    
    
    
    
  } 
  private void setICanChangeUserName(boolean can) {
    bChangeUserName.setEnabled(can);
    bDeleteUser.setEnabled(!can);
  }

  private void this_componentShown(ComponentEvent e) {
    labCurrentUserLogin.setText(currentUserLoginLabel + ": " + connAssist.getUserName()); 
    tfReaderName.setText(connAssist.getReaderName());
    setICanChangeUserName(false);
  }

  private void ChangeUserName_actionPerformed(ActionEvent e) {
    String newReaderName = tfReaderName.getText();
    try {      
      PreparedStatement st = 
        connAssist.getConn().prepareStatement("update READER set NAME = ? where CODE = user"); 
      st.setString(1, newReaderName);
      st.executeUpdate();
      st.close();
      connAssist.setReaderName(newReaderName);
      connAssist.readerNameChanged();
      setICanChangeUserName(false);
    } catch (Exception ex) {ErrorShower.show(this, "changing user name", "", ex);} 
  }

  private void bClose_actionPerformed(ActionEvent e) {
    this_windowClosing(null);
  }

  private void this_windowClosing(WindowEvent e) {
    if(bChangeUserName.isEnabled()) {
      int confirmResult = 
        JOptionPane.showConfirmDialog(this, General.getLangItem("userNameWasChanged", "The user " +
        "name was changed but was not applied. \nDo you want to close the window anyway?"), 
        General.getLangItem("Question", "Question"), JOptionPane.YES_NO_OPTION, 
        JOptionPane.QUESTION_MESSAGE); 
      if(confirmResult == JOptionPane.YES_OPTION) this.setVisible(false);
    } else this.setVisible(false);
  }

  private void bNewUser_actionPerformed(ActionEvent e) {
    DialogNewUser fr = new DialogNewUser(this, "", true);
    fr.setConn(connAssist.getConn());
    fr.setVisible(true);
  }

  private void bDeleteUser_actionPerformed(ActionEvent e) {
    /*System.out.println(labCurrentUserLogin.getSize().toString());
    System.out.println(labReaderName.getSize().toString());
    System.out.println(tfReaderName.getSize().toString());
    System.out.println(bChangeUserName.getSize().toString());
    System.out.println(bNewUser.getSize().toString());
    System.out.println(bDeleteUser.getSize().toString());
    System.out.println(bClose.getSize().toString());*/
    // Пугаем пользователя предупреждением 
    int confirmResult = 
      JOptionPane.showConfirmDialog(this, General.getLangItem("sureToDeleteYourselfQuest", 
      "Do you really want to delete the current user? Deleting a user will make him \n" + 
      "impossible to connect to the database. Also all the words that were unchecked \n" +
      "by this user will be deleted. This action cannot be undone. Continue? \n" +
      "After deletion you will be disconnected and this dialog will be closed."), 
      General.getLangItem("WarningExcl", "Warning!"), JOptionPane.YES_NO_OPTION, 
      JOptionPane.WARNING_MESSAGE); 
    // Ну а если он не испугался, то удаляем его нах...
    if(confirmResult == JOptionPane.NO_OPTION) return;
    try {
      CallableStatement st = connAssist.getConn().prepareCall("{call DELETE_CURRENT_USER()}");
      st.executeUpdate();
      st.close();
    } catch(Exception ex) {ErrorShower.show(this, "deleting current new user", "", ex); return;}
    // Отключаемся и закрываем эту форму 
    try {connAssist.disconnect();} 
    catch(Exception ex) {ErrorShower.show(this, "disconnect", "", ex);}
    this.setVisible(false);
  }
  //
  
  
}